
#ifndef WISHMASTER_RECAPTCHAFETCHER_IMPL_H
#define WISHMASTER_RECAPTCHAFETCHER_IMPL_H

#include <QObject>
#include "log.h"
#include "components/threadid.h"
#include "components/chan.h"
#include "requestmanager.h"

namespace Wishmaster
{
	class RecaptchaFetcherImpl : public QObject
	{
		Q_OBJECT
	public:
		RecaptchaFetcherImpl()
		{
		}

		void setRequestManager(Wishmaster2::Network::RequestManager* requestManager)
		{
			m_requestManager = requestManager;
		}

		void setParams(const QVariantMap& params)
		{
			for(QVariantMap::const_iterator it = params.begin(); it != params.end(); ++it)
			{
				if(it.key() == "recaptcha_key")
				{
					m_recaptchaKey = it.value().toString();
				}
			}
		}

		void fetchCaptcha(const ThreadId& threadId)
		{
			Wishmaster2::Network::Url url(std::string("http://www.google.com/recaptcha/api/challenge?k=") + m_recaptchaKey.toStdString()); // FIXME hardcoded
			Wishmaster2::Network::RequestPtr rq = m_requestManager->createRequest(url);
			rq->connectSignalFinished(boost::bind(&RecaptchaFetcherImpl::challenge, this, _1));
			m_requestManager->enqueueRequest(rq);
			m_threadId = threadId;
		}

		void processRequest(const PostDescriptor& post, const QString& captcha, const Wishmaster2::Network::RequestPtr& request)
		{
			request->setParameter("recaptcha_challenge_field", m_challenge.toStdString());
			request->setParameter("recaptcha_response_field", captcha.toStdString());
		}

	signals:
		void captcha(const ThreadId& threadId, const QByteArray& arr);

	private:
		void challenge(int requestId)
		{
			Wishmaster2::Network::RequestPtr rq = m_requestManager->request(requestId);
			QString str = QString::fromUtf8(rq->content()->data(), rq->content()->size());
			QRegExp rx("challenge\\s*:\\s*'([^']*)'");
			if(rx.indexIn(str) < 0)
			{
				log(llError, "recaptchafetcher: Unable to locate challenge (%d)", rq->content()->size());
				return;
			}
			m_challenge = rx.cap(1);
			log(llDebug, "Challenge: %s", qPrintable(m_challenge));

			Wishmaster2::Network::Url url(std::string("http://www.google.com/recaptcha/api/image?c=") + m_challenge.toStdString()); // FIXME hardcoded
			Wishmaster2::Network::RequestPtr newRequest = m_requestManager->createRequest(url);
			newRequest->connectSignalFinished(boost::bind(&RecaptchaFetcherImpl::slot_captcha, this, _1));
			m_requestManager->enqueueRequest(newRequest);
		}

		void slot_captcha(int requestId)
		{
			Wishmaster2::Network::RequestPtr rq = m_requestManager->request(requestId);
			QByteArray arr(rq->content()->data(), rq->content()->size());
			emit captcha(m_threadId, arr);
		}

	private:
		Wishmaster2::Network::RequestManager* m_requestManager;
		QString m_recaptchaKey;
		QString m_challenge;
		ThreadId m_threadId;
	};
}

#endif

